-- lua tail.lua file n
-- output the last n lines

function printLastNLines (file, n)
	local file = io.open(file, "r")
	if not file then
		print("open file error")
		return
	end
	if n <= 0 then return end

	local lines = {}
	local size = file:seek("end", 0)
	local line = ""
	local char

	while size > 0 do
		size = size - 1
		file:seek("set", size)
		char = file:read(1)

		if char == "\n" then
			table.insert(lines, file:read("l"))
			if #lines == n then
				break
			end
		end
	end

	for i = #lines, 1, -1 do
		print(lines[i])
	end

	file:close()
end

function run ()
	if arg[1] == nil then
		return
	elseif arg[2] == nil then
		printLastNLines(arg[1], 1)
	else
		printLastNLines(arg[1], tonumber(arg[2]))
	end
end

run()
